<?php
namespace app\applet\controller;

use app\applet\model\Applet as AppletModel;
use app\applet\model\Wechat as WechatModel;
use think\facade\Session;
use hema\wechat\Driver;

/**
 * 授权回调接口
 */

class Auth extends \app\BaseController
{
	/**
     * 微信公众号授权
     */
    public function wechat($applet_id = 0)
    {
		$auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );	//获取授权码
		if(!empty($auth_code)){
			$wx = new Driver;
			//获取授权信息
			if(!$auth = $wx->getAuth($auth_code)){
			    die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
			}
			//获取授权应用的帐号基本信息
			if(!$result = $wx->getAppInfo($auth['authorizer_appid'])){
			    die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
			}
			$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
			if($wechat = WechatModel::getWechat([
			    'app_id' => $auth['authorizer_appid']
			   ])){
			    die(hema_json(['code' => 0, 'msg' => '该公众号已存在，wechat_id:'.$wechat['wechat_id'].'，请选择其它公众号完成授权绑定操作']));
			}
			if($wechat = WechatModel::getWechat(['applet_id' => $applet_id])){
				if(!empty($wechat['app_id']) AND $wechat['app_id'] != $auth['authorizer_appid']){
					$wechat->clear($applet_id);//切换授权 - 清除历史数据
				}
			}else{
				$wechat = new WechatModel;
			}
			$wechat->save([
				'app_id' => $auth['authorizer_appid'],//授权方APPid
				'user_name' => $app['user_name'],//原始ID
				'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
				'head_img' => isset($app['head_img'])?$app['head_img']:'',//头像
				'qrcode_url' =>$app['qrcode_url'],	//二维码地址
				'principal_name' => $app['principal_name'],	//主体名称
				'access_token' => $auth['authorizer_access_token'],	//令牌
				'expires_in' => time()+7000,//令牌过期时间
				'authorizer_refresh_token' => $auth['authorizer_refresh_token'],//刷新令牌	
				'applet_id' => $applet_id,	
				'status' => 1	//是否授权		
			]);
			if($applet_id > 0){
				return redirect('/applet/wechat/index');
			}
			return redirect('/admin/wechat/index');
		}
		echo "error";
	}

	/**
     * 微信小程序授权
     */
    public function wxapp($applet_id = 0)
    {
		$auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );	//获取授权码
		if(!empty($auth_code)){
			$wx = new Driver;
			//获取授权信息
			if(!$auth = $wx->getAuth($auth_code)){
			    die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
			}
			$applet = AppletModel::getApplet(['app_id' => $auth['authorizer_appid']]);
			//验证是否重复授权小程序
			if($applet and $applet['applet_id'] != $applet_id){
			    die(hema_json(['code' => 0, 'msg' => '该小程序已存在，applet_id:'.$applet['applet_id'].'，请选择其它小程序完成授权绑定操作']));
			}
			$applet = AppletModel::get($applet_id);
			//获取授权应用的帐号基本信息
			if(!$result = $wx->getAppInfo($auth['authorizer_appid'])){
			    die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
			}
			$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
			//如果已经进行了绑定，不允许切换
			if(!empty($applet['app_id']) AND $applet['app_id'] != $auth['authorizer_appid']){
				die(hema_json(['code' => 0, 'msg' => '不允许切换绑定其它小程序']));
			}
			$api_domain = '';
            $signature = '';
            //添加服务器域名
            if(!$result = $wx->setServeDomain(0,'',$auth['authorizer_access_token'])){
                die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
            }
             $api_domain = $result['apiurl'];
            //设置小程序简介
            if(!$result = $wx->setSignature(0,'',$auth['authorizer_access_token'])){
                die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
            }
            $signature = $result['signature'];
			$applet->save([
				'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
				'head_img' => isset($app['head_img'])?$app['head_img']:'',		//头像
				'qrcode_url' => isset($app['qrcode_url'])?$app['qrcode_url']:'',	//二维码
				'user_name' => $app['user_name'],					//原始ID
				'principal_name' => $app['principal_name'],			//主体名称
				'signature' => $signature,	//账号介绍
				'api_domain' => $api_domain,//服务器域名
				'app_id' => $auth['authorizer_appid'],				//授权方APPid
				'access_token' => $auth['authorizer_access_token'],	//令牌
				'expires_in' => time()+7000,						//令牌过期时间
				'authorizer_refresh_token' => $auth['authorizer_refresh_token'],	//刷新令牌
				'status' => 1	//是否授权				
			]);
			// 保存授权状态
			$applet = AppletModel::get($applet_id);
			Session::set('hema_applet.applet',$applet);
			return redirect('/applet/wxapp/index');
		}
		echo "error";
	}
}
